package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        /*缓存穿透:不存在时存入空值,命中时对空值的判断*/
        //Shop shop = queryByIdWithPassThrough(id);
        //缓存击穿:加锁解决(互斥锁)
        Shop shop = queryByIdWithMutex(id);
        //缓存击穿:逻辑过期解决
        //Shop shop = queryByIdWithLogicalExpire(id);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }


    /**
     * 缓存穿透解决方法
     *
     * @param id
     * @return
     */
    public Shop queryByIdWithPassThrough(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1. 查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2. 缓存存在，
        // 直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断查询缓存是否命中空值
        if (shopJson != null) {
            return null;
        }
        //3. 缓存不存在，查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //4. 数据库不存在，返回错误
            return null;
        }
        //5. 数据库存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 缓存击穿解决方法(互斥锁)
     *
     * @param id
     * @return
     */
    public Shop queryByIdWithMutex(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1. 查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2. 缓存存在，直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断查询缓存是否命中空值
        if (shopJson != null) {
            return null;
        }
        //3. 缓存不存在,实现缓存重建
        // 4. 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;

        // 使用循环代替递归调用
        while (true) {
            try {
                boolean isLock = tryLock(lockKey);
                if (!isLock) {
                    // 获取锁失败，休眠并重试
                    Thread.sleep(50);
                    continue; // 重新尝试获取锁
                }

                // 4. 获取锁成功后再次检查 Redis 缓存
                shopJson = stringRedisTemplate.opsForValue().get(key);
                if (StrUtil.isNotBlank(shopJson)) {
                    // 缓存已存在，直接返回
                    return JSONUtil.toBean(shopJson, Shop.class);
                }

                if (shopJson != null) {
                    // 缓存为空值，直接返回 null
                    return null;
                }

                // 5. 缓存仍不存在，根据 id 查询数据库
                shop = getById(id);

                if (shop == null) {
                    // 将空值写入 Redis，设置较短的 TTL
                    stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null; // 数据库不存在，返回错误
                }

                // 6. 数据库存在，写入 Redis
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
                break; // 成功写入缓存后退出循环
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
                throw new RuntimeException("Thread interrupted while acquiring lock", e);
            } catch (Exception e) {
                // 捕获其他异常并记录日志
                log.error("Error occurred during cache rebuild for shop ID: {}", id, e);
                throw new RuntimeException("Failed to rebuild cache", e);
            } finally {
                // 7. 释放锁
                unLock(lockKey);
            }
        }
        return shop;
    }

    /**
     * 使用逻辑过期解决缓存击穿问题
     *
     * @param id 店铺ID
     * @return 店铺信息
     */
    public Shop queryByIdWithLogicalExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 1. 查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 缓存不存在，直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        // 3. 缓存存在，解析数据
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Object data = redisData.getData();
        Shop shop = JSONUtil.toBean((JSONObject) data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        // 4. 判断是否逻辑过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，直接返回数据
            return shop;
        }

        // 5. 已过期，尝试获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 再次判断是否逻辑过期
            if (expireTime.isAfter(LocalDateTime.now())) {
                // 未过期，直接返回数据
                return shop;
            }
            // 获取锁成功，开启独立线程异步重建缓存
            RedisConstants.CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 重建缓存
                    saveShopToCache(id, RedisConstants.CACHE_SHOP_TTL);
                } catch (Exception e) {
                    log.error("Error occurred during cache rebuild for shop ID: {}", id, e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        // 返回旧数据（无论是否获取到锁）
        return shop;
    }


    /**
     * 将店铺数据保存到缓存，并设置逻辑过期时间
     *
     * @param id  店铺ID
     * @param ttl 缓存有效时间（分钟）
     */
    private void saveShopToCache(Long id, Long ttl) {
        // 查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            return; // 数据库中不存在该店铺，无需缓存
        }
        // 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(ttl));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(
                RedisConstants.CACHE_SHOP_KEY + id,
                JSONUtil.toJsonStr(redisData)
        );
    }

    /**
     * 获取互斥锁
     *
     * @param lockKey
     * @return
     */
    private boolean tryLock(String lockKey) {
        boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(isLock);
    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    private void unLock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }

    @Override
    @Transactional
    public void update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            throw new RuntimeException("id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        log.info("更新商铺信息,删除缓存");
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
    }
}
